package com.ruoyi.project.tickets.service.impl;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.List;

import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.framework.security.LoginUser;
import com.ruoyi.framework.security.service.TokenService;
import com.ruoyi.project.common.utils.CommonUtil;
import com.ruoyi.project.tickets.domain.*;
import com.ruoyi.project.tickets.domain.constant.TicketsConstant;
import com.ruoyi.project.tickets.domain.dto.OutStockDto;
import com.ruoyi.project.tickets.domain.dto.SaleDto;
import com.ruoyi.project.tickets.domain.vo.SaleVo;
import com.ruoyi.project.tickets.mapper.StockMapper;
import com.ruoyi.project.tickets.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.OrderUtils;
import org.springframework.stereotype.Service;
import com.ruoyi.project.tickets.mapper.SaleMapper;
import org.springframework.transaction.annotation.Transactional;

/**
 * 销售概况Service业务层处理
 *
 * @author 孙山伟
 * @date 2023-07-01
 */
@Service
public class SaleServiceImpl implements ISaleService {
    @Autowired
    private SaleMapper saleMapper;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private StockMapper stockMapper;
    @Autowired
    private ISaleDetailsService saleDetailsService;
    @Autowired
    private IShopService shopService;
    @Autowired
    private ISaleService saleService;
    @Autowired
    private ISerialService serialService;

    @Autowired
    private IOutStockService outStockService;
    @Autowired
    private IShopUserService shopUserService;
    @Autowired
    private ITicketsRuleService ticketsRuleService;

    /**
     * 查询销售概况
     *
     * @param id 销售概况ID
     * @return 销售概况
     */
    @Override
    public Sale selectSaleById(Long id) {
        return saleMapper.selectSaleById(id);
    }

    /**
     * 查询销售概况列表
     *
     * @param sale 销售概况
     * @return 销售概况
     */
    @Override
    public List<SaleVo> selectSaleList(Sale sale) {

        return saleMapper.selectSaleList(sale);
    }

    /**
     * 新增销售概况
     *
     * @param saleDto 销售概况
     * @return 结果
     */
    @Override
    @Transactional
    public int insertSale(SaleDto saleDto) {
        try {
            LoginUser user = tokenService.getLoginUser(ServletUtils.getRequest());
            ShopUser shopUser = new ShopUser();
            shopUser.setUserId(user.getUser().getUserId());
            List<ShopUser> shopUserList = shopUserService.selectShopUserList(shopUser);
            if (ObjectUtil.isNull(shopUserList)) {
                shopUser.setShopId(-1L);
            } else {
                if (shopUserList.size() == 0) {
                    shopUser.setShopId(-1L);
                } else {
                    shopUser.setShopId(shopUserList.get(0).getShopId());
                }
            }
            Shop shop=shopService.selectShopById(shopUser.getShopId());
            Long sum = saleDto.getStockList().stream().mapToLong(OutStockDto::getNumber).sum();
            //增加售卖基本情况

            Sale sale = new Sale();
            sale.setAmount(saleDto.getAmount());
            sale.setSettleType(saleDto.getSettleType());
            sale.setShopTime(DateUtils.getNowDate());
            sale.setShopId(shopUser.getShopId());
            sale.setUserId(user.getUser().getUserId());
            sale.setCreateTime(DateUtils.getNowDate());
            sale.setTotalNumber(sum);
            saleMapper.insertSale(sale);

            for (OutStockDto dto : saleDto.getStockList()) {

                //售卖详情
                SaleDetails saleDetails = new SaleDetails();
                Stock stock = stockMapper.selectStockById(dto.getStockId());
                TicketsRule rule=ticketsRuleService.selectTicketsRuleById(stock.getRuleId());
                saleDetails.setRuleId(stock.getRuleId());
                saleDetails.setSaleId(sale.getId());
                saleDetails.setSaleNumber(dto.getNumber());
                double amount= dto.getNumber()*rule.getTotalPrice();
                DecimalFormat format=new DecimalFormat("#0.00");
                saleDetails.setSaleAmount(new BigDecimal(format.format(amount)));
                saleDetails.setCreateBy(user.getUsername());
                saleDetails.setCreateTime(sale.getCreateTime());
                saleDetailsService.insertSaleDetails(saleDetails);
                int i = 1;
                //核销数据初
                while (i <= dto.getNumber()*rule.gettNum()) {
                    Serial serial = new Serial();
                    serial.setIsOff(TicketsConstant.IS_NO_OFF);
                    serial.setRuleId(stock.getRuleId());
                    serial.setSaleId(sale.getId());
                    serial.setShopId(shopUser.getShopId());
                    serial.setCreateBy(user.getUser().getUserId().toString());
                    serial.setSerialNumber(CommonUtil.genOrderNum(user.getUser().getUserId()));
                    serial.setCode(CommonUtil.getCode(shop.getCode()));
                    serialService.insertSerial(serial);
                    i++;

                }

            }
            //出库情况
            outStockService.insertOutStock(saleDto.getStockList());
        } catch (Exception e) {
            e.getMessage();
            return 0;
        }
        return 1;
    }

    /**
     * 修改销售概况
     *
     * @param sale 销售概况
     * @return 结果
     */
    @Override
    public int updateSale(Sale sale) {
        sale.setUpdateTime(DateUtils.getNowDate());
        return saleMapper.updateSale(sale);
    }

    /**
     * 批量删除销售概况
     *
     * @param ids 需要删除的销售概况ID
     * @return 结果
     */
    @Override
    public int deleteSaleByIds(Long[] ids) {
        return saleMapper.deleteSaleByIds(ids);
    }

    /**
     * 删除销售概况信息
     *
     * @param id 销售概况ID
     * @return 结果
     */
    @Override
    public int deleteSaleById(Long id) {
        return saleMapper.deleteSaleById(id);
    }

    @Override
    public List<SaleVo> selectReprotList(Sale sale) {
        return saleMapper.selectReprotList(sale);
    }

    @Override
    public List<Sale> selectList(Sale sale) {
        return saleMapper.selectList(sale);
    }
}
